<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="租户编码" prop="tenantId">
        <el-input v-model="queryParams.tenantId" placeholder="请输入租户编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="租户名称" prop="tenantName">
        <el-input v-model="queryParams.tenantName" placeholder="请输入租户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否激活" prop="activeFlag" v-show="showSearch">
        <el-select v-model="queryParams.activeFlag" placeholder="请选择是否激活" clearable size="small">
          <el-option :key="0" label="禁用" :value="0" />
          <el-option :key="1" label="激活" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="模板" prop="tempId">
        <el-select v-model="queryParams.tempId" clearable filterable placeholder="请选择模板">
          <el-option v-for="item in this.templateList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="search">
        <hide-search :show-search.sync="showSearch"></hide-search>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-content">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:tenant:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:tenant:edit']">修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" plain icon="el-icon-delete" class="btn-delete" size="mini" :disabled="multiple" @click="handleDelete"-->
<!--          v-hasPermi="['system:tenant:remove']">删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:tenant:export']">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租户编码" align="center" prop="tenantId" />
      <el-table-column label="租户名称" align="center" prop="tenantName" />
      <el-table-column label="登录账号" align="center" prop="account" />
      <!--      <el-table-column label="地址" align="center" prop="address" />-->
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="有效截止时间" align="center" prop="activeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否激活" align="center" prop="activeFlag" :formatter="activeFlagFormat" />
      <el-table-column label="模板" align="center" prop="tempName" :formatter="tempNameFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tenant:edit']">修改</el-button>
<!--          <el-button size="mini" icon="el-icon-delete" class="btn-delete" @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:tenant:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    </div>
    <!-- 添加或修改租户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租户模板" prop="tempId">
          <el-select v-model="form.tempId" filterable placeholder="请选择租户模板" @change="selectChange">
            <el-option v-for="item in this.templateList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入租户登录账号"  :disabled="title === '修改租户信息' "/>
        </el-form-item>
        <el-form-item label="地址" prop="regionCodes">
          <RegionSelect v-model="form.regionCodes"></RegionSelect>
        </el-form-item>
        <el-form-item label="" prop="address">
          <el-input type="textarea" v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <!-- <el-input v-model="form.phone" placeholder="请输入电话" :disabled="form.tempId" /> -->
          <el-input v-model="form.phone" placeholder="请输入电话" :disabled="title === '修改租户信息'" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="截止时间" prop="activeTime">
          <el-date-picker clearable v-model="form.activeTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择有效截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否激活" prop="activeFlag">
          <el-radio-group v-model="form.activeFlag">
            <el-radio :key="1" :label="1">激活</el-radio>
            <el-radio :key="0" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addTenant,
    delTenant,
    getTenant,
    listTenant,
    updateTenant
  } from "@/api/system/tenant";
  import {
    listTemplate
  } from "@/api/system/template";
  import RegionSelect from "@/views/components/RegionSelect";

  // 邮箱
  const IsEmail = (rule, value, callback) => {
    const reg = /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/;
    if (!reg.test(value)) {
      callback(new Error('请输入正确的邮箱'));
    } else {
      callback();
    }
  };
  export default {
    name: "Tenant",
    components: {
      RegionSelect
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        // 租户信息表格数据
        tenantList: [],
        //所有权限模板
        templateList: [],
        templateMap: {},
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          tenantId: undefined,
          tenantName: undefined,
          account: undefined,
          address: undefined,
          phone: undefined,
          email: undefined,
          activeTime: undefined,
          activeFlag: undefined,
          tempId: undefined,
          regionCodes: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          tenantName: [{
            required: true,
            message: "租户名称不能为空",
            trigger: "blur"
          }],
          account: [{
            required: true,
            message: "租户登录账号不能为空",
            trigger: "blur"
          }],
          phone: [{
              required: true,
              message: "手机号不能为空",
              trigger: "blur"
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          email: [{
              required: true,
              message: "邮箱不能为空",
              trigger: "blur"
            },
            {
              validator: IsEmail,
              trigger: 'blur'
            }
          ],
          activeTime: [{
            required: true,
            message: "有效截止时间不能为空",
            trigger: "blur"
          }],
          activeFlag: [{
            required: true,
            message: "是否激活不能为空",
            trigger: "blur"
          }],
          tempId: [{
            required: true,
            message: "权限模板不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
      this.initTemplates();
    },
    methods: {
      /** 查询租户信息列表 */
      getList() {
        this.loading = true;
        listTenant(this.queryParams).then(response => {
          this.tenantList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 是否激活字典翻译
      activeFlagFormat(row, column) {
        let show = "";
        if (row.activeFlag === 0) {
          show = "禁用";
        } else if (row.activeFlag === 1) {
          show = "激活";
        }
        return show;
      },
      tempNameFormat(row, column) {
        let name = this.templateMap[row.tempId];
        return name ? name : row.tempId;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          tenantId: undefined,
          tenantName: undefined,
          address: undefined,
          phone: undefined,
          email: undefined,
          createTime: undefined,
          activeTime: undefined,
          activeFlag: 1,
          tempId: undefined,
          regionCodes: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加租户信息";
        this.initTemplates();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids
        getTenant(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改租户信息";
          this.initTemplates();
        });
      },
      initTemplates() {
        // 查询所有可选模板
        listTemplate().then(response => {
          this.templateList = response.rows;
          this.templateMap = {};
          this.templateList.forEach(item => {
            this.templateMap[item.id] = item.name;
          })
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateTenant(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addTenant(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(() => {
          this.loading = true;
          return delTenant(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/tenant/export', {
          ...this.queryParams
        }, `tenant_${new Date().getTime()}.xlsx`)
      },
      selectChange(val) {
        this.$refs['form'].clearValidate(['tempId']);
      }
    }

  };

</script>
